<!DOCTYPE html>
<html lang="zh-CN">
<head>
  <meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=2">
<meta name="theme-color" content="#222">
<meta name="generator" content="Hexo 5.4.0">


  <link rel="apple-touch-icon" sizes="180x180" href="/images/apple-touch-icon-next.png">
  <link rel="icon" type="image/png" sizes="32x32" href="/images/favicon-32x32-next.png">
  <link rel="icon" type="image/png" sizes="16x16" href="/images/favicon-16x16-next.png">
  <link rel="mask-icon" href="/images/logo.svg" color="#222">

<link rel="stylesheet" href="/css/main.css">



<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/@fortawesome/fontawesome-free@5.15.2/css/all.min.css">
  <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/animate.css@3.1.1/animate.min.css">

<script class="hexo-configurations">
    var NexT = window.NexT || {};
    var CONFIG = {"hostname":"littlefxc.github.io","root":"/","images":"/images","scheme":"Mist","version":"8.2.2","exturl":false,"sidebar":{"position":"left","display":"post","padding":18,"offset":12},"copycode":false,"bookmark":{"enable":false,"color":"#222","save":"auto"},"fancybox":false,"mediumzoom":false,"lazyload":false,"pangu":false,"comments":{"style":"tabs","active":null,"storage":true,"lazyload":false,"nav":null},"motion":{"enable":true,"async":false,"transition":{"post_block":"fadeIn","post_header":"fadeInDown","post_body":"fadeInDown","coll_header":"fadeInLeft","sidebar":"fadeInUp"}},"prism":false,"i18n":{"placeholder":"搜索...","empty":"没有找到任何搜索结果：${query}","hits_time":"找到 ${hits} 个搜索结果（用时 ${time} 毫秒）","hits":"找到 ${hits} 个搜索结果"},"path":"/search.xml","localsearch":{"enable":true,"trigger":"auto","top_n_per_article":1,"unescape":false,"preload":false}};
  </script>
<meta name="description" content="[TOC] 引言下面这张图是 Java 中比较主流的基于分代收集理论的垃圾收集器，以及它们能够作用的JVM内存区域。  术语 STW：全局停顿，Java 代码停止运行，native 代码继续运行，但不能与 JVM 进行交互。  STW 原因：多半由于垃圾回收导致；也可能是由 Dump 线程、死锁检查和 Dump 堆等导致的。  STW 危害：服务停止、毫无响应；主从切换、危害生产环境。    并行">
<meta property="og:type" content="article">
<meta property="og:title" content="JVM 垃圾收集器">
<meta property="og:url" content="http://littlefxc.github.io/2022/03/11/docs/JVM/JVM-%E5%9E%83%E5%9C%BE%E6%94%B6%E9%9B%86%E5%99%A8/index.html">
<meta property="og:site_name" content="一年春又来">
<meta property="og:description" content="[TOC] 引言下面这张图是 Java 中比较主流的基于分代收集理论的垃圾收集器，以及它们能够作用的JVM内存区域。  术语 STW：全局停顿，Java 代码停止运行，native 代码继续运行，但不能与 JVM 进行交互。  STW 原因：多半由于垃圾回收导致；也可能是由 Dump 线程、死锁检查和 Dump 堆等导致的。  STW 危害：服务停止、毫无响应；主从切换、危害生产环境。    并行">
<meta property="og:locale" content="zh_CN">
<meta property="og:image" content="https://gitee.com/littlefxc/oss/raw/master/images/image-20220311164628901.png">
<meta property="og:image" content="https://gitee.com/littlefxc/oss/raw/master/images/image-20220311171643510.png">
<meta property="og:image" content="https://gitee.com/littlefxc/oss/raw/master/images/image-20220311173051813.png">
<meta property="og:image" content="https://gitee.com/littlefxc/oss/raw/master/images/image-20220314152651631.png">
<meta property="og:image" content="https://gitee.com/littlefxc/oss/raw/master/images/image-20220314161053707.png">
<meta property="og:image" content="https://gitee.com/littlefxc/oss/raw/master/images/image-20220314161516210.png">
<meta property="og:image" content="https://gitee.com/littlefxc/oss/raw/master/images/image-20220314162206027.png">
<meta property="og:image" content="https://gitee.com/littlefxc/oss/raw/master/images/image-20220314171405933.png">
<meta property="og:image" content="https://gitee.com/littlefxc/oss/raw/master/images/image-20220316150715171.png">
<meta property="article:published_time" content="2022-03-11T00:45:21.000Z">
<meta property="article:modified_time" content="2022-05-10T01:24:27.498Z">
<meta property="article:author" content="一年春又来">
<meta property="article:tag" content="jvm">
<meta name="twitter:card" content="summary">
<meta name="twitter:image" content="https://gitee.com/littlefxc/oss/raw/master/images/image-20220311164628901.png">


<link rel="canonical" href="http://littlefxc.github.io/2022/03/11/docs/JVM/JVM-%E5%9E%83%E5%9C%BE%E6%94%B6%E9%9B%86%E5%99%A8/">


<script class="page-configurations">
  // https://hexo.io/docs/variables.html
  CONFIG.page = {
    sidebar: "",
    isHome : false,
    isPost : true,
    lang   : 'zh-CN'
  };
</script>
<title>JVM 垃圾收集器 | 一年春又来</title>
  




  <noscript>
  <style>
  body { margin-top: 2rem; }

  .use-motion .menu-item,
  .use-motion .sidebar,
  .use-motion .post-block,
  .use-motion .pagination,
  .use-motion .comments,
  .use-motion .post-header,
  .use-motion .post-body,
  .use-motion .collection-header {
    visibility: visible;
  }

  .use-motion .header,
  .use-motion .site-brand-container .toggle,
  .use-motion .footer { opacity: initial; }

  .use-motion .site-title,
  .use-motion .site-subtitle,
  .use-motion .custom-logo-image {
    opacity: initial;
    top: initial;
  }

  .use-motion .logo-line {
    transform: scaleX(1);
  }

  .search-pop-overlay, .sidebar-nav { display: none; }
  .sidebar-panel { display: block; }
  </style>
</noscript>

<link rel="alternate" href="/atom.xml" title="一年春又来" type="application/atom+xml">
</head>

<body itemscope itemtype="http://schema.org/WebPage" class="use-motion">
  <div class="headband"></div>

  <main class="main">
    <header class="header" itemscope itemtype="http://schema.org/WPHeader">
      <div class="header-inner"><div class="site-brand-container">
  <div class="site-nav-toggle">
    <div class="toggle" aria-label="切换导航栏" role="button">
        <span class="toggle-line"></span>
        <span class="toggle-line"></span>
        <span class="toggle-line"></span>
    </div>
  </div>

  <div class="site-meta">

    <a href="/" class="brand" rel="start">
      <i class="logo-line"></i>
      <h1 class="site-title">一年春又来</h1>
      <i class="logo-line"></i>
    </a>
  </div>

  <div class="site-nav-right">
    <div class="toggle popup-trigger">
        <i class="fa fa-search fa-fw fa-lg"></i>
    </div>
  </div>
</div>



<nav class="site-nav">
  <ul class="main-menu menu">
        <li class="menu-item menu-item-home"><a href="/" rel="section"><i class="home                          //首页 fa-fw"></i>首页</a></li>
        <li class="menu-item menu-item-archives"><a href="/archives/" rel="section"><i class="archive          //归档 fa-fw"></i>归档</a></li>
        <li class="menu-item menu-item-categories"><a href="/categories/" rel="section"><i class="th           //分类 fa-fw"></i>分类</a></li>
        <li class="menu-item menu-item-tags"><a href="/tags/" rel="section"><i class="tags                     //标签 fa-fw"></i>标签</a></li>
      <li class="menu-item menu-item-search">
        <a role="button" class="popup-trigger"><i class="fa fa-search fa-fw"></i>搜索
        </a>
      </li>
  </ul>
</nav>



  <div class="search-pop-overlay">
    <div class="popup search-popup"><div class="search-header">
  <span class="search-icon">
    <i class="fa fa-search"></i>
  </span>
  <div class="search-input-container">
    <input autocomplete="off" autocapitalize="off" maxlength="80"
           placeholder="搜索..." spellcheck="false"
           type="search" class="search-input">
  </div>
  <span class="popup-btn-close" role="button">
    <i class="fa fa-times-circle"></i>
  </span>
</div>
<div class="search-result-container no-result">
  <div class="search-result-icon">
    <i class="fa fa-spinner fa-pulse fa-5x"></i>
  </div>
</div>

    </div>
  </div>

</div>
        
  
  <div class="toggle sidebar-toggle" role="button">
    <span class="toggle-line"></span>
    <span class="toggle-line"></span>
    <span class="toggle-line"></span>
  </div>

  <aside class="sidebar">

    <div class="sidebar-inner sidebar-nav-active sidebar-toc-active">
      <ul class="sidebar-nav">
        <li class="sidebar-nav-toc">
          文章目录
        </li>
        <li class="sidebar-nav-overview">
          站点概览
        </li>
      </ul>

      <div class="sidebar-panel-container">
        <!--noindex-->
        <div class="post-toc-wrap sidebar-panel">
            <div class="post-toc animated"><ol class="nav"><li class="nav-item nav-level-2"><a class="nav-link" href="#%E5%BC%95%E8%A8%80"><span class="nav-text">引言</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#%E6%9C%AF%E8%AF%AD"><span class="nav-text">术语</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#%E5%9E%83%E5%9C%BE%E6%94%B6%E9%9B%86%E5%99%A8%E4%BB%8B%E7%BB%8D"><span class="nav-text">垃圾收集器介绍</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#Serial-%E6%94%B6%E9%9B%86%E5%99%A8%EF%BC%88%E6%96%B0%E7%94%9F%E4%BB%A3%EF%BC%89"><span class="nav-text">Serial 收集器（新生代）</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#ParNew%E6%94%B6%E9%9B%86%E5%99%A8%EF%BC%88%E6%96%B0%E7%94%9F%E4%BB%A3%EF%BC%89"><span class="nav-text">ParNew收集器（新生代）</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#Parallel-Scavenge%E6%94%B6%E9%9B%86%E5%99%A8%EF%BC%88%E6%96%B0%E7%94%9F%E4%BB%A3%EF%BC%89"><span class="nav-text">Parallel Scavenge收集器（新生代）</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#Serial-Old-%E6%94%B6%E9%9B%86%E5%99%A8%EF%BC%88%E8%80%81%E5%B9%B4%E4%BB%A3%EF%BC%89"><span class="nav-text">Serial Old 收集器（老年代）</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#Parallel-Old-%E6%94%B6%E9%9B%86%E5%99%A8%EF%BC%88%E8%80%81%E5%B9%B4%E4%BB%A3%EF%BC%89"><span class="nav-text">Parallel Old 收集器（老年代）</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#CMS-%E6%94%B6%E9%9B%86%E5%99%A8%EF%BC%88%E8%80%81%E5%B9%B4%E4%BB%A3%EF%BC%89"><span class="nav-text">CMS 收集器（老年代）</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#G1-%E6%94%B6%E9%9B%86%E5%99%A8"><span class="nav-text">G1 收集器</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#G1-%E6%94%B6%E9%9B%86%E5%99%A8-VS-CMS%E6%94%B6%E9%9B%86%E5%99%A8"><span class="nav-text">G1 收集器 VS CMS收集器</span></a></li></ol></li><li class="nav-item nav-level-2"><a class="nav-link" href="#%E9%93%BE%E6%8E%A5"><span class="nav-text">链接</span></a></li></ol></div>
        </div>
        <!--/noindex-->

        <div class="site-overview-wrap sidebar-panel">
          <div class="site-author site-overview-item animated" itemprop="author" itemscope itemtype="http://schema.org/Person">
  <p class="site-author-name" itemprop="name">一年春又来</p>
  <div class="site-description" itemprop="description"></div>
</div>
<div class="site-state-wrap site-overview-item animated">
  <nav class="site-state">
      <div class="site-state-item site-state-posts">
          <a href="/archives/">
        
          <span class="site-state-item-count">234</span>
          <span class="site-state-item-name">日志</span>
        </a>
      </div>
      <div class="site-state-item site-state-categories">
            <a href="/categories/">
          
        <span class="site-state-item-count">38</span>
        <span class="site-state-item-name">分类</span></a>
      </div>
      <div class="site-state-item site-state-tags">
            <a href="/tags/">
          
        <span class="site-state-item-count">125</span>
        <span class="site-state-item-name">标签</span></a>
      </div>
  </nav>
</div>



        </div>
      </div>
    </div>
  </aside>
  <div class="sidebar-dimmer"></div>


    </header>

    
  <div class="back-to-top" role="button">
    <i class="fa fa-arrow-up"></i>
    <span>0%</span>
  </div>

<noscript>
  <div class="noscript-warning">Theme NexT works best with JavaScript enabled</div>
</noscript>


    <div class="main-inner post posts-expand">


  


<div class="post-block">
  
  

  <article itemscope itemtype="http://schema.org/Article" class="post-content" lang="zh-CN">
    <link itemprop="mainEntityOfPage" href="http://littlefxc.github.io/2022/03/11/docs/JVM/JVM-%E5%9E%83%E5%9C%BE%E6%94%B6%E9%9B%86%E5%99%A8/">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="image" content="/images/avatar.gif">
      <meta itemprop="name" content="一年春又来">
      <meta itemprop="description" content="">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="一年春又来">
    </span>
      <header class="post-header">
        <h1 class="post-title" itemprop="name headline">
          JVM 垃圾收集器
        </h1>

        <div class="post-meta-container">
          <div class="post-meta">
    <span class="post-meta-item">
      <span class="post-meta-item-icon">
        <i class="far fa-calendar"></i>
      </span>
      <span class="post-meta-item-text">发表于</span>

      <time title="创建时间：2022-03-11 08:45:21" itemprop="dateCreated datePublished" datetime="2022-03-11T08:45:21+08:00">2022-03-11</time>
    </span>
      <span class="post-meta-item">
        <span class="post-meta-item-icon">
          <i class="far fa-calendar-check"></i>
        </span>
        <span class="post-meta-item-text">更新于</span>
        <time title="修改时间：2022-05-10 09:24:27" itemprop="dateModified" datetime="2022-05-10T09:24:27+08:00">2022-05-10</time>
      </span>
    <span class="post-meta-item">
      <span class="post-meta-item-icon">
        <i class="far fa-folder"></i>
      </span>
      <span class="post-meta-item-text">分类于</span>
        <span itemprop="about" itemscope itemtype="http://schema.org/Thing">
          <a href="/categories/Java/" itemprop="url" rel="index"><span itemprop="name">Java</span></a>
        </span>
    </span>

  
</div>

        </div>
      </header>

    
    
    
    <div class="post-body" itemprop="articleBody">
        <p>[TOC]</p>
<h2 id="引言"><a href="#引言" class="headerlink" title="引言"></a>引言</h2><p>下面这张图是 Java 中比较主流的基于分代收集理论的垃圾收集器，以及它们能够作用的JVM内存区域。</p>
<p><img src="https://gitee.com/littlefxc/oss/raw/master/images/image-20220311164628901.png" alt="image-20220311164628901"></p>
<h2 id="术语"><a href="#术语" class="headerlink" title="术语"></a>术语</h2><ul>
<li><p>STW：全局停顿，Java 代码停止运行，native 代码继续运行，但不能与 JVM 进行交互。</p>
<ul>
<li><p>STW 原因：多半由于垃圾回收导致；也可能是由 Dump 线程、死锁检查和 Dump 堆等导致的。</p>
</li>
<li><p>STW 危害：服务停止、毫无响应；主从切换、危害生产环境。</p>
</li>
</ul>
</li>
<li><p>并行收集：指多个垃圾回收线程并行工作，但是收集的过程中，用户线程还是处于等待状态。</p>
</li>
<li><p>并发收集：指用户线程与垃圾收集线程同时工作。</p>
</li>
<li><p>吞吐量：CPU 用于运行用户代码的时间与 CPU 总消耗时间的对比</p>
<ul>
<li>公式：运行用户代码时间/(运行用户代码时间+垃圾收集时间)</li>
</ul>
</li>
</ul>
<h2 id="垃圾收集器介绍"><a href="#垃圾收集器介绍" class="headerlink" title="垃圾收集器介绍"></a>垃圾收集器介绍</h2><h3 id="Serial-收集器（新生代）"><a href="#Serial-收集器（新生代）" class="headerlink" title="Serial 收集器（新生代）"></a>Serial 收集器（新生代）</h3><p><img src="https://gitee.com/littlefxc/oss/raw/master/images/image-20220311171643510.png" alt="image-20220311171643510"></p>
<ul>
<li>最基本的、历史最悠久的收集器</li>
<li>算法：复制算法</li>
<li>特点：<ul>
<li>简单、高效</li>
<li>单线程</li>
<li>垃圾回收过程中 STW</li>
</ul>
</li>
</ul>
<h3 id="ParNew收集器（新生代）"><a href="#ParNew收集器（新生代）" class="headerlink" title="ParNew收集器（新生代）"></a>ParNew收集器（新生代）</h3><p><img src="https://gitee.com/littlefxc/oss/raw/master/images/image-20220311173051813.png" alt="image-20220311173051813"></p>
<ul>
<li><p>Serial 收集器的多线程版，除了使用多线程外，其它的和Serial收集器一样。</p>
</li>
<li><p>特点：</p>
<ul>
<li>多线程</li>
<li>可以设置垃圾收集的线程数（-XX:ParallelGCThreads）</li>
</ul>
</li>
<li><p>使用场景：主要用来和 CMS 收集器配合使用</p>
</li>
</ul>
<h3 id="Parallel-Scavenge收集器（新生代）"><a href="#Parallel-Scavenge收集器（新生代）" class="headerlink" title="Parallel Scavenge收集器（新生代）"></a>Parallel Scavenge收集器（新生代）</h3><p><img src="https://gitee.com/littlefxc/oss/raw/master/images/image-20220314152651631.png" alt="image-20220314152651631"></p>
<ul>
<li>关注的是吞吐量，也叫吞吐量收集器</li>
<li>采用的也是复制算法</li>
<li>也是并行的多线程收集器，这一点和 ParNew 类似</li>
<li>特点：<ul>
<li>可以达到一个可控制的吞吐量，有两个 JVM 参数可以配置：<ul>
<li>-XX:MaxGCPauseMillis:控制最大的垃圾收集停顿时间（尽力）</li>
<li>-XX:GCTimeRatio:设置吞吐量的大小，取值 0-100， 系统花费不超过 1/(1+n) 的时间用于垃圾收集</li>
</ul>
</li>
<li>自适应 GC 策略：可用 -XX:+UseAdptiveSizePolicy 打开<ul>
<li>打开自适应策略后，无需手动设置新生代的大小（-Xmn）、Eden 与 Survivor 区的比例（-XX:SurvivorRatio）等参数</li>
<li>虚拟机会自动根据系统的运行状况收集性能情况，动态的调整这些参数，从而达到最优的停顿时间以及最高的的吞吐量</li>
</ul>
</li>
</ul>
</li>
<li>使用场景：注重吞吐量的场景</li>
</ul>
<h3 id="Serial-Old-收集器（老年代）"><a href="#Serial-Old-收集器（老年代）" class="headerlink" title="Serial Old 收集器（老年代）"></a>Serial Old 收集器（老年代）</h3><p><img src="https://gitee.com/littlefxc/oss/raw/master/images/image-20220314161053707.png" alt="image-20220314161053707"></p>
<ul>
<li>Serial收集器的老年代</li>
<li>算法：标记-整理</li>
<li>使用场景：<ul>
<li>可以和 Serial、ParNew、Parallel Scavenge 这三个新生代的垃圾收集器配合使用</li>
<li>CMS 收集器出现故障的时候，会用 Serial Old 作为后备</li>
</ul>
</li>
</ul>
<h3 id="Parallel-Old-收集器（老年代）"><a href="#Parallel-Old-收集器（老年代）" class="headerlink" title="Parallel Old 收集器（老年代）"></a>Parallel Old 收集器（老年代）</h3><p><img src="https://gitee.com/littlefxc/oss/raw/master/images/image-20220314161516210.png" alt="image-20220314161516210"></p>
<ul>
<li>Parallel Scavenge 收集器的老年代版本</li>
<li>算法：标记整理</li>
<li>特点：只能和 Parallel Scavenge 配合使用</li>
<li>使用场景：关注吞吐量的场景</li>
</ul>
<h3 id="CMS-收集器（老年代）"><a href="#CMS-收集器（老年代）" class="headerlink" title="CMS 收集器（老年代）"></a>CMS 收集器（老年代）</h3><p>全称叫做 Concurrent Mark Sweep</p>
<p><img src="https://gitee.com/littlefxc/oss/raw/master/images/image-20220314162206027.png" alt="image-20220314162206027"></p>
<ul>
<li><p>并发收集器</p>
</li>
<li><p>算法：标记-清除</p>
</li>
<li><p>CMS 收集器执行过程</p>
<ul>
<li><strong>初始标记</strong>（initial mark）<ul>
<li>标记 GC Roots 能直接关联到的对象 </li>
<li>Stop The World</li>
</ul>
</li>
<li><strong>并发标记</strong>（concurrent mark）<ul>
<li>找出所有 GC Roots 能关联到的对象</li>
<li>并发执行，无 Stop The World</li>
</ul>
</li>
<li>并发预清理（concurrent-preclean）<ul>
<li>重新标记那些在并发标记阶段，引用被更新的对象，从而减少后面重新标记阶段的工作量</li>
<li>并发执行，无 Stop The World</li>
<li>可用 -XX:-CMSPrecleaningEnabled 关闭并发预发清理阶段，默认打开。</li>
</ul>
</li>
<li>并发可中止的预清理阶段（concurrent-abort-oreclan）<ul>
<li>和并发预清理做的事一样，并发执行，无 StopTheWorld。</li>
<li>当 Eden 的使用量大于 CMSScheduleRemarkEdenSizeThreashold 的阈值（默认 2M）时，才会执行该阶段</li>
<li>主要作用：允许我们能够控制预清理阶段的结束时机。比如扫描多长时间（CMSMaxAbortablePrecleanTime， 默认 5 秒）或者 Eden 区使用占比打到一定阈值（CMSScheduleRemarkEdenPenetration，默认 50%）就结束本阶段</li>
</ul>
</li>
<li><strong>重新标记</strong><ul>
<li>修正并发标记期间，因为用户程序继续运行，导致标记发生变动的那些对象的标记</li>
<li>一般来说，重新标记花费的时间会比初始标记阶段长一点，但比并发标记的时间短</li>
<li>存在 Stop The World</li>
</ul>
</li>
<li><strong>并发清除</strong><ul>
<li>基于标记结果，清除掉要清除前面标记出来的垃圾</li>
<li>并发执行，无 Stop The World</li>
</ul>
</li>
<li><strong>并发重置</strong><ul>
<li>清理本次 CMS GC 的上下文信息，为下一次 GC 做准备</li>
</ul>
</li>
</ul>
</li>
<li><p>优点：</p>
<ul>
<li>Stop The World 的时间比较短，只有初始标记和重新标记阶段存在 Stop The World，其它阶段都是并发执行的</li>
<li>大多数的过程都是并发执行的</li>
</ul>
</li>
<li><p>缺点：</p>
<ul>
<li><p>CPU 资源比较敏感：并发阶段可能导致应用吞吐量的降低</p>
</li>
<li><p>无法处理浮动垃圾（并发清除阶段时，用户线程生产出来的垃圾，无法在本次收集时间内处理）</p>
</li>
<li><p>不能等老年代几乎满了才开始收集</p>
<ul>
<li>预留的内存不够 -&gt;  Concurrent Mode Failure -&gt; Serial Old 作为后备</li>
<li>CMSInitiatingOccupancyFraction 设置老年代占比达到多少就触发垃圾收集，默认 68%</li>
</ul>
</li>
<li><p>内存碎片</p>
<ul>
<li>标记-清除导致碎片的产生</li>
<li>UseCMSCompactAtFullCollection：在完成 Full GC 后是否要进行内存碎片整理，默认开启</li>
<li>CMSFullGCsBeforeCompaction：进行几次 Full GC 后就进行一次内存碎片整理，默认 0</li>
</ul>
</li>
</ul>
</li>
<li><p>使用场景：</p>
<ul>
<li>希望系统停顿时间短，响应速度快的场景，比如各种应用程序</li>
</ul>
</li>
</ul>
<h3 id="G1-收集器"><a href="#G1-收集器" class="headerlink" title="G1 收集器"></a>G1 收集器</h3><ul>
<li><p>Garbge First</p>
</li>
<li><p>面向服务端应用的垃圾收集器</p>
</li>
<li><p>内存布局<br><img src="https://gitee.com/littlefxc/oss/raw/master/images/image-20220314171405933.png" alt="image-20220314171405933"></p>
<ul>
<li>将整个JVM分成若干个大小相等的区域，每个区域叫做 Region</li>
<li>每个 Region的大小可通过 -XX:G1HeapRegionSize 指定 Region 的大小</li>
<li>Region 取值范围为 1M～32M，应为 2 的 N 次幂</li>
<li>Region 的分类：Eden、survivor、Old、Humongous</li>
<li>在 G1 里面，同一个代里面的对象可能是不连续的</li>
<li>Humongous 是用来存储大对象的，某个对象超过了 Region的一半就认为是大对象，如果对象超级大，就放在多个联系的 humongous 里面</li>
<li>G1 会将 Humongous 也看作老年代来处理</li>
</ul>
</li>
<li><p>设计思想</p>
<ul>
<li>若干个 Region</li>
<li>跟踪每个 Region 里面的垃圾堆积的价值大小</li>
<li>G1 在后台构建一个优先列表，根据允许的收集时间，优先回收价值高的 Region，这样就可以获得更高的回收效率</li>
</ul>
</li>
<li><p>垃圾收集机制</p>
<ul>
<li><p>Young GC</p>
<ul>
<li>当所有的Eden都满了的时候，就会触发 Young GC，</li>
<li>所有的 Eden 里面的对象会转移到 Survivor Region 里面去，</li>
<li>而原先 Survivor Region 里面的对象转移到新的Survivor Region中，或者晋升到 Old Region，</li>
<li>最后，空闲Region会被放入空闲列表中，等待下次被使用</li>
</ul>
</li>
<li><p>Mixed GC</p>
<ul>
<li><p>当老年代大小占整个堆的百分比达到一定阈值（可用<code>-XX:InitiatingHeapOccupancyPercent</code>指定，默认 45%），就触发 Mixed GC，</p>
</li>
<li><p>Mixed GC 会回收所有 Young Region，同时回收<strong>部分</strong> Old Region，</p>
</li>
<li><p>Mixed GC 执行过程</p>
<p><img src="https://gitee.com/littlefxc/oss/raw/master/images/image-20220316150715171.png" alt="image-20220316150715171"></p>
<ul>
<li>初始标记，标记 GC Roots 能直接关联到的对象，和 CMS 类似，<strong>存在</strong> Stop The World</li>
<li>并发标记，同 CMS 的并发标记，并发执行，<strong>没有</strong> Stop The World</li>
<li>最终标记，修正在并发标记期间引起的变动，<strong>存在</strong> Stop The World</li>
<li>筛选回收，对各个Region的回收价值和成本进行排序，根据用户所期望的的停顿时间（根据MaxGCPauseMillis来指定）来制定回收计划，并选择一些 Region 回收，回收过程如下：<ul>
<li>选择一系列 Region 构成一个回收集</li>
<li>把决定回收的 Region 中的存活对象复制到空的 Region 中</li>
<li>删掉需回收的Region（无内存碎片）</li>
</ul>
</li>
</ul>
</li>
</ul>
</li>
<li><p>Full GC</p>
<ul>
<li>复制对象的内存不够，或者无法分配足够的内存（比如，巨型对象没有足够的连续分区分配）时，会触发Full GC，</li>
<li>Full GC 模式下，使用 Serial Old 模式，</li>
<li>因此 G1 的优化原则就是尽量减少 Full GC 的发生。</li>
<li>那么，如何减少Full GC呢？<ul>
<li>增加预留内存（增大 -XX:G1ReservePercent，默认为堆的 10%）；</li>
<li>更早地回收垃圾（减少 -XX:InitatingHeapOccupancyPercent，老年代达到该阈值就会触发 Mixed GC，默认 45%）；</li>
<li>增加并发阶段使用的线程数（增大 -XX:ConcGCThreads）</li>
</ul>
</li>
</ul>
</li>
</ul>
</li>
<li><p>特点：</p>
<ul>
<li>可以作用在整个堆、</li>
<li>可控的停顿（MaxGCPauseMillis=200）、</li>
<li>无内存碎片</li>
</ul>
</li>
<li><p>使用场景：</p>
<ul>
<li>占用内存较大的应用（6G 以上）</li>
<li>替换 CMS 垃圾收集器</li>
</ul>
</li>
</ul>
<h3 id="G1-收集器-VS-CMS收集器"><a href="#G1-收集器-VS-CMS收集器" class="headerlink" title="G1 收集器 VS CMS收集器"></a>G1 收集器 VS CMS收集器</h3><p>对于JDK 8：都可以用</p>
<ul>
<li>如果内存小于等于 6G，建议用 CMS，如果内存大于6G，考虑使用 G1。</li>
</ul>
<p>如果 JDK 版本大于 8 以上，则用 G1， 因为从 JDK9 开始，CMS已被废弃了。</p>
<h2 id="链接"><a href="#链接" class="headerlink" title="链接"></a>链接</h2><ol>
<li><p><a target="_blank" rel="noopener" href="https://blog.csdn.net/Little_fxc/article/details/122603669?spm=1001.2014.3001.5502">分代收集理论</a></p>
<p>本文所讲述的垃圾收集器都是基于分代收集理论的</p>
</li>
<li><p><a target="_blank" rel="noopener" href="https://blog.csdn.net/Little_fxc/article/details/114004380?ops_request_misc=%257B%2522request%255Fid%2522%253A%2522164698905416780269867798%2522%252C%2522scm%2522%253A%252220140713.130102334.pc%255Fblog.%2522%257D&request_id=164698905416780269867798&biz_id=0&utm_medium=distribute.pc_search_result.none-task-blog-2~blog~first_rank_ecpm_v1~rank_v31_ecpm-5-114004380.nonecase&utm_term=JVM&spm=1018.2226.3001.4450">JVM内存结构简单分析</a></p>
<p>垃圾收集器回收的都有哪些JVM内存区域，这些内存区域在JVM中是怎么分布的？分别有哪些数据？</p>
</li>
<li><p><a target="_blank" rel="noopener" href="https://blog.csdn.net/Little_fxc/article/details/123266153?spm=1001.2014.3001.5501">JVM-垃圾回收算法</a></p>
<p>本文提到的垃圾收集器所使用的垃圾回收算法的原理</p>
</li>
<li><p><a target="_blank" rel="noopener" href="https://blog.csdn.net/Little_fxc/article/details/123210008?spm=1001.2014.3001.5501">JVM-垃圾回收</a></p>
<p>提到的 GC Roots 是怎么回事</p>
</li>
</ol>

    </div>

    
    
    

    <footer class="post-footer">
          <div class="post-tags">
              <a href="/tags/jvm/" rel="tag"># jvm</a>
          </div>

        

          <div class="post-nav">
            <div class="post-nav-item">
                <a href="/2022/03/01/docs/JVM/JVM-%E5%9E%83%E5%9C%BE%E5%9B%9E%E6%94%B6%E7%AE%97%E6%B3%95/" rel="prev" title="JVM 垃圾回收算法">
                  <i class="fa fa-chevron-left"></i> JVM 垃圾回收算法
                </a>
            </div>
            <div class="post-nav-item">
                <a href="/2022/03/16/docs/JVM/JVM-%E5%85%B6%E5%AE%83%E5%9E%83%E5%9C%BE%E6%94%B6%E9%9B%86%E5%99%A8/" rel="next" title="JVM 其它垃圾收集器">
                  JVM 其它垃圾收集器 <i class="fa fa-chevron-right"></i>
                </a>
            </div>
          </div>
    </footer>
  </article>
</div>







<script>
  window.addEventListener('tabs:register', () => {
    let { activeClass } = CONFIG.comments;
    if (CONFIG.comments.storage) {
      activeClass = localStorage.getItem('comments_active') || activeClass;
    }
    if (activeClass) {
      const activeTab = document.querySelector(`a[href="#comment-${activeClass}"]`);
      if (activeTab) {
        activeTab.click();
      }
    }
  });
  if (CONFIG.comments.storage) {
    window.addEventListener('tabs:click', event => {
      if (!event.target.matches('.tabs-comment .tab-content .tab-pane')) return;
      const commentClass = event.target.classList[1];
      localStorage.setItem('comments_active', commentClass);
    });
  }
</script>
</div>
  </main>

  <footer class="footer">
    <div class="footer-inner">


<div class="copyright">
  &copy; 
  <span itemprop="copyrightYear">2022</span>
  <span class="with-love">
    <i class="fa fa-heart"></i>
  </span>
  <span class="author" itemprop="copyrightHolder">一年春又来</span>
</div>
  <div class="powered-by">由 <a href="https://hexo.io/" class="theme-link" rel="noopener" target="_blank">Hexo</a> & <a href="https://theme-next.js.org/mist/" class="theme-link" rel="noopener" target="_blank">NexT.Mist</a> 强力驱动
  </div>

    </div>
  </footer>

  
  <script src="https://cdn.jsdelivr.net/npm/animejs@3.2.1/lib/anime.min.js"></script>
<script src="/js/utils.js"></script><script src="/js/motion.js"></script><script src="/js/schemes/muse.js"></script><script src="/js/next-boot.js"></script>

  
<script src="/js/local-search.js"></script>






  





</body>
</html>
